#!/bin/bash


#### 需要配置的变量  等号两边不要留空格,不要在windows下编辑
src_host=198.199.108.10
src_db_name=root
src_db_pwd=123456
src_db_schema=appbricks

dst_host=104.236.154.96
dst_user_name=core
dst_ssh_file="/home/wzq/office/digitalocean_104.236.154.96"
dst_file_dir=/home/core/backup/mysql

local_docker_name=mysql_v3 # 如果本地没有mysqldump,可以从docker中获取
#### 需要配置的变量  等号两边不要留空格,不要在windows下编辑



##### 不需要配置的变量
file_name=mysql_${src_db_schema}_`date +'%Y-%m-%d'`.sql
# echo $file_name

#### step1. mysqldump must exist
if [ -z "$local_docker_name" ]; then
    mysql &> /dev/null
    if [ $? -eq 127 ]  ; then
        echo "mysql not exist"
        exit 1
    fi
fi


#### step2.  mysql dump
echo "backup start at `date +'%Y-%m-%d %H:%M:%S'`"
_mysqldump="mysqldump -h $src_host -u $src_db_name -p$src_db_pwd --databases $src_db_schema > $file_name"
if [ ! -z "$local_docker_name" ]; then
    _mysqldump="docker exec $local_docker_name sh -c 'mysqldump -h $src_host -u $src_db_name -p$src_db_pwd --databases $src_db_schema' > $file_name"
fi

echo $_mysqldump
eval $_mysqldump



#### step3. mkdir
# ssh -i $dst_ssh_file $dst_user_name@$dst_host -t "mkdir -p $dst_file_dir"



#### step4. compress and send
_scp="tar zcvf - $file_name  | ssh -i $dst_ssh_file $dst_user_name@$dst_host 'mkdir -p $dst_file_dir; cat > $dst_file_dir/$file_name.tgz' "
echo $_scp
eval $_scp
echo "backup success at `date +'%Y-%m-%d %H:%M:%S'` "


#### step5. cleanup
#rm $file_name